package com.example.openai.controller.helloController;

import com.example.openai.model.LoginUser;
import com.example.openai.model.User;
import com.example.openai.service.LoginService;
import com.example.openai.util.RedisCache;
import com.example.openai.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LoginService loginService;
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        ResponseResult responseResult=loginService.login(user);
        return responseResult;
    }
    @RequestMapping("/user/loginout")
    public  ResponseResult loginout(){
        UsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser) authentication.getPrincipal();
        Long id = principal.getUser().getId();
        redisCache.deleteObject("login:"+id);
        return new  ResponseResult(200,"退出成功");
    }
}
